﻿#include "reminder.h"

Reminder::Reminder(QObject *parent,const QSqlDatabase &db) : QObject(parent),_db(db)
{
    generateSchema();
}

void Reminder::generateSchema()
{
    cleanUp();

    if(!timers.isEmpty())
    {
        QHash<QString,QTimer*>::const_iterator itor;
        for(itor=timers.constBegin();itor != timers.constEnd();itor++)
            itor.value()->deleteLater();
        timers.clear();
    }

    QSqlQuery query(_db);
    query.exec(QString("select uid,target from %1 where host='%2'")
               .arg(TD_ONCE)
               .arg(QHostInfo::localHostName()));

    while(query.next())
    {
        QString uid=query.value(0).toString();
        QDateTime target=query.value(1).toDateTime();
        int offset=QDateTime::currentDateTime().secsTo(target);

        Timer *timer=new Timer(this,uid);
        timer->setSingleShot(true);
        connect(timer,&Timer::raise,this,&Reminder::timerRaise);
        timer->start(offset * 1000);
        timers.insert(uid, timer);
    }
}

void Reminder::cleanUp()
{
    QSqlQuery query(_db);
    query.exec(QString("select uid,target from %1 where host='%2'")
               .arg(TD_ONCE)
               .arg(QHostInfo::localHostName()));

    while(query.next())
    {
        QString uid=query.value(0).toString();
        QDateTime target=query.value(1).toDateTime();
        int offset=QDateTime::currentDateTime().secsTo(target);
        if(offset <= 0)
        {
            QSqlQuery query(_db);
            query.exec(QString("delete from %1 where uid='%2'").arg(TD_ONCE).arg(uid));
        }
    }
}

void Reminder::timerRaise(const QString &uid)
{
    QSqlQuery query(_db);
    query.exec(QString("select detail from %1 where uid = '%2'")
               .arg(TD_ONCE)
               .arg(uid));
    query.next();

    emit raise(query.value(0).toString());
}
